<template>
  <div class="card">
    <div class="card-body">
      <h5 class="font-weight-bold mb-5">修改密码</h5>

      <el-form label-width="120px" :model="form" :rules="rules" ref="form">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            placeholder="原密码"
            class="w-input"
            type="password"
            v-model="form.oldPassword"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            placeholder="新密码"
            class="w-input"
            type="password"
            v-model="form.newPassword"
          ></el-input>
        </el-form-item>
        <el-form-item label="重复密码" prop="ainPassword">
          <el-input
            placeholder="再次输入新密码"
            class="w-input"
            type="password"
            v-model="form.ainPassword"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :loading="loading">修 改</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { resetPassword } from '@/common/api/auth'

export default {
  components: {},

  props: {},

  data() {
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      form: {
        oldPassword: '',
        newPassword: '',
        ainPassword: '',
      },
      rules: {
        oldPassword: [{ required: true, message: '请填写旧密码', trigger: 'blur' }],
        newPassword: [{ required: true, message: '请填写新密码', trigger: 'blur' }],
        ainPassword: [{ validator: validatePass, trigger: 'blur' }],
      },
      loading: false,
    }
  },

  computed: {},

  watch: {},

  created() {},

  mounted() {},

  methods: {
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.putPassword()
        } else {
          this.$message.error('输入错误，请重新输入！')
        }
      })
    },

    putPassword() {
      this.loading = true
      resetPassword({
        oldPassword: this.form.oldPassword,
        newPassword: this.form.newPassword,
      })
        .then(res => {
          if (res.data > 0) {
            this.$message.success('修改密码成功！')
            this.$refs.form.resetFields()
          } else {
            this.$message.error('修改密码错误，请重试！')
          }
        })
        .catch(() => {
          this.$message.error('修改密码错误，请重试！')
        })
        .then(() => {
          this.loading = false
        })
    },
  },
}
</script>

<style scoped>
.w-input {
  max-width: 250px;
}
</style>
